package com.sunway.android.services;

import java.util.ArrayList;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

import android.app.Service;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import com.warefont.lepad.MINA.MessagesClient;
import com.warefont.lepad.beans.LFDEntity;
import com.warefont.lepad.beans.LFDPoolEntity;	
import com.warefont.lepad.utils.AsyncImageLoader;
import com.warefont.lepad.utils.JSONUtils;

public class MessagesService extends Service {

	public static final int MSG_REGISTER_CLIENT = 1;
	public static final int MSG_UNREGISTER_CLIENT = 2;
	public static final int MSG_SEND_MESSAGE_TO_REMOTE_SERVER = 3;
	public static final int MSG_SEND_TO_ACTIVITY_LOAD_LFTPOOL = 4;
	public static final int MSG_SEND_TO_ACTIVITY_LOAD_LFT = 5;
	public static final int MSG_TYPE_LFD_POOL_ENTITY_LIST = 6;
	public static final int MSG_TYPE_LFD_UPDATE_ENTITY = 7;
	public static final int MSG_TYPE_LFD_ENTITY_LIST = 8;
	public static final int MSG_SEND_TO_LOGIN_ACTIVITY_FOR_PASSWORD_CHECKING = 9;
	public static final int MSG_TYPE_LOGIN_ACTIVITY_PASSWORD_CHECKING = 10;
	public static final int MSG_TYPE_REQUEST_ALARM_LIST = 11;
	public static final int MSG_SEND_TO_ALARM_LIST_ACTIVITY_FOR_ALARM_LIST = 12;
	public static final int MSG_SEND_TO_ALARM_LIST_ACTIVITY_FOR_ALARM_EVERY_GRADE_COUNT = 13;
	public static final int MSG_SEND_TO_ALARM_LIST_ACTIVITY_FOR_ALARM_CLASS_ITEM_LIST = 14;
	public static final int MSG_SET_REMOTE_IP = 15;
	public static final int MSG_REMOTE_SESSION_IS_OK = 16;
	public static final int MSG_REMOTE_SESSION_IS_NOT_OK = 17;

	private boolean onBind = false;

	private MessagesClient messagesClient = null;
	private ArrayList<Messenger> messengerClients = new ArrayList<Messenger>();
	private IoSession session = null;

	private final Messenger socketServerMessenger = new Messenger(
			new IncomingHandler());
	private AsyncImageLoader asyncImageLoader = new AsyncImageLoader();

	@Override
	public IBinder onBind(Intent intent) {
		return socketServerMessenger.getBinder();
	}

	@Override
	public void onCreate() {
//		super.onCreate();
		messagesClient = new MessagesClient(new IoHandlerAdapter() {
			@Override
			public void messageReceived(IoSession session, Object message)
					throws Exception {
				String[] messagesArray = message.toString().split("\\|\\|\\|");
				Log.d("myDebug", messagesArray[1]);
				int messageType = Integer.parseInt(messagesArray[0]);
				Log.d("myDebug", "messageType:" + messageType);
				// Message receivedMessage = new Message();
				Message receivedMessage = Message.obtain();

				switch (messageType) {
				case MSG_TYPE_LFD_POOL_ENTITY_LIST: {
					receivedMessage.what = MSG_SEND_TO_ACTIVITY_LOAD_LFTPOOL;
					ArrayList<LFDPoolEntity> lfdPoolEntityList = JSONUtils.parseLFDPoolEntityFromJson(messagesArray[1]);

					// 预加载所有图片
					for (int i = lfdPoolEntityList.size() - 1; i >= 0; i--) {
						LFDPoolEntity lfdPoolEntity = lfdPoolEntityList.get(i);
						asyncImageLoader.loadDrawable(
								lfdPoolEntity.getOverviewImg(),
								new AsyncImageLoader.ImageCallback() {
									@Override
									public void imageLoaded(
											Drawable imageDrawable) {
									}
								});
					}

					receivedMessage.obj = new Object[] { lfdPoolEntityList,
							asyncImageLoader };
					break;
				}
				case MSG_TYPE_LFD_ENTITY_LIST: {
					receivedMessage.what = MSG_SEND_TO_ACTIVITY_LOAD_LFT;
					ArrayList<LFDEntity> lfdEntityList = JSONUtils
							.parseLFDEntityFromJson(messagesArray[1]);

					// 预加载所有图片
					for (int i = lfdEntityList.size() - 1; i >= 0; i--) {
						LFDEntity lfdEntity = lfdEntityList.get(i);
						asyncImageLoader.loadDrawable(
								lfdEntity.getOverviewImg(),
								new AsyncImageLoader.ImageCallback() {
									@Override
									public void imageLoaded(
											Drawable imageDrawable) {
									}
								});
					}

					receivedMessage.obj = new Object[] { lfdEntityList,
							asyncImageLoader };
					break;
				}

				case MSG_TYPE_LOGIN_ACTIVITY_PASSWORD_CHECKING: {
					receivedMessage.what = MSG_SEND_TO_LOGIN_ACTIVITY_FOR_PASSWORD_CHECKING;
					receivedMessage.obj = new String((String) messagesArray[1]);
					break;
				}

				case MSG_SEND_TO_ALARM_LIST_ACTIVITY_FOR_ALARM_LIST: {
					receivedMessage.what = MSG_SEND_TO_ALARM_LIST_ACTIVITY_FOR_ALARM_LIST;
					receivedMessage.obj = new String((String) messagesArray[1]);
					break;
				}
				case MSG_SEND_TO_ALARM_LIST_ACTIVITY_FOR_ALARM_EVERY_GRADE_COUNT: {
					receivedMessage.what = MSG_SEND_TO_ALARM_LIST_ACTIVITY_FOR_ALARM_EVERY_GRADE_COUNT;
					receivedMessage.obj = new String((String) messagesArray[1]);
					break;
				}
				case MSG_SEND_TO_ALARM_LIST_ACTIVITY_FOR_ALARM_CLASS_ITEM_LIST: {
					receivedMessage.what = MSG_SEND_TO_ALARM_LIST_ACTIVITY_FOR_ALARM_CLASS_ITEM_LIST;
					receivedMessage.obj = new String((String) messagesArray[1]);
					break;
				}
				}

				for (int i = messengerClients.size() - 1; i >= 0; i--) {
					try {
						Messenger messenger = messengerClients.get(i);
						Message messageTemp = Message.obtain();
						messageTemp.copyFrom(receivedMessage);
						messenger.send(messageTemp);
						// messageTemp.recycle();
					} catch (RemoteException e) {
						messengerClients.remove(i);
					}
				}

				receivedMessage.recycle();

				Log.d("myDebug", message.toString());
			}

			@Override
			public void sessionCreated(IoSession session) throws Exception {
				MessagesService.this.session = session;
				if (!onBind) {
					session.write("doBind");// 向服务器发送绑定请求
					onBind = true;
				}

				Message receivedMessage = Message.obtain();
				receivedMessage.what = MSG_REMOTE_SESSION_IS_OK;
				receivedMessage.obj = "Session is OK!";
				for (int i = messengerClients.size() - 1; i >= 0; i--) {
					try {
						Messenger messenger = messengerClients.get(i);
						Message messageTemp = Message.obtain();
						messageTemp.copyFrom(receivedMessage);
						messenger.send(messageTemp);
					} catch (RemoteException e) {
						messengerClients.remove(i);
					}
				}
			}
		}, this);

	}

	private class IncomingHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_REGISTER_CLIENT:
				// Log.d("MSG_REGISTER_CLIENT", msg.replyTo.toString());
				messengerClients.add(msg.replyTo);
				break;
			case MSG_UNREGISTER_CLIENT:
				messengerClients.remove(msg.replyTo);
				break;
			case MSG_SEND_MESSAGE_TO_REMOTE_SERVER:
				session.write((String) msg.obj);
				// Log.d("myDebug", "session.write((String) msg.obj)");
				break;
			case MSG_SET_REMOTE_IP:
				messagesClient.startClient((String) msg.obj);
				Log.d("myDebug", "MSG_SET_REMOTE_IP" + (String) msg.obj);
				break;
			default:
				super.handleMessage(msg);
			}
		}
	}

	public void sentRemoteIpIsNotOk() {
		Message receivedMessage = Message.obtain();
		receivedMessage.what = MSG_REMOTE_SESSION_IS_NOT_OK;
		for (int i = messengerClients.size() - 1; i >= 0; i--) {
			try {
				Messenger messenger = messengerClients.get(i);
				Message messageTemp = Message.obtain();
				messageTemp.copyFrom(receivedMessage);
				messenger.send(messageTemp);
			} catch (RemoteException e) {
				messengerClients.remove(i);
			}
		}
	}

}
